import {
  getHomeCasual,
  getHomeNav,
  getGoodsList,
  getRecommendList,
  getSearchGoods,
  login_auto,
  loginout,
  alertUserInfo,
  getCart
} from '../api/index'

import {
  HOME_CASUAL,
  HOME_NAV,
  GOODS_LIST,
  RECOMMEND_LIST,
  SEARCH_LIST,
  USER_INFO,
  RESET_USER_INFO,
  SHOP_CART,
  ADD_GOODS_COUNT,
  REDUCE_GOODS_COUNT,
  SELECT_ALL,
  SELECT,
  DELETE_SINGLE
} from './mutation-type'

export default {
  // 获取首页轮播图
  async reqHomeCasual({commit}){
    const result = await getHomeCasual();
    commit(HOME_CASUAL,{homecasual:result.message})
  },
  // 请求首页导航数据
  async reqHomeNav({commit}){
    const result = await getHomeNav();
    commit(HOME_NAV,{homenav:result.message});
  },
  // 请求首页商品列表数据
  async reqGoodsList({commit}){
    const result = await getGoodsList();
    commit(GOODS_LIST,{goodslist:result.message.goods_list});
  },
  // 请求推荐页数据
  async reqRecommendList({commit},parsms){
    const result =await getRecommendList(parsms);
    commit(RECOMMEND_LIST,{recommendlist:result.message});
    parsms.callback && parsms.callback();
  },
  // 获取搜索页商品分类数据
  async reqSearchGoods({commit}){
    const result =await getSearchGoods();
    commit(SEARCH_LIST,{searchlist:result.message.data});
  },
  // 同步用户信息
  syncUserInfo({commit},userInfo){
    commit(USER_INFO,{userInfo});
  },

  // 异步获取用户信息
  async getUserInfo({commit},params){
    let result = await login_auto();
    if(result.success_code == 200){
      commit(USER_INFO,{userInfo:result.message});
    }else {
      params.callback(result.message);
    }
  },

  // 退出登录(因为要操作state，所以得通过mutation和action)
  async getLoginOut({commit}){
    let retult = await loginout();
    if(retult.success_code == 200){
      commit(RESET_USER_INFO);
    }
  },

  // 修改用户信息
  async alertUserInfo({commit},params){
    let result = await alertUserInfo(params);
    if(result.success_code == 200){
      commit(USER_INFO,{userInfo:result.messages});
    }
  },

  // 获取购物车信息
  async getShopCart({commit}){
    let result = await getCart();
    if(result.success_code === 200){
      commit(SHOP_CART,{shopCart:result.messages});
    }
  },
  // 单个商品的增加或减少
  updateGoods({commit},{goods,isAdd}){
    if(isAdd){ // 增加
      commit(ADD_GOODS_COUNT,{goods});
    }else { // 减少
      commit(REDUCE_GOODS_COUNT,{goods});
    }
  },
  // 是否选中所有商品
  isSelectAll({commit},isSelect){  // actions往mutation中提交负载的参数是以对象的形式；而其本身接收一个及以上的参数才用对象的形式
    commit(SELECT_ALL,{isSelect});
  },
  // 选中单个商品
  isSelect({commit},goods){
    commit(SELECT,{goods});
  },
  // 单个商品的删除
  deleteSingle({commit},goods){
    commit(DELETE_SINGLE,{goods});
  }
}
